package com.mmd.common.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mmd.bean.CODE;
import com.mmd.bean.WebJsonBean;
import com.mmd.exception.GameException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author cyq
 * @Date 2019/8/30 21:25
 * @Description
 **/
public class GlobalExceptionHandler  implements HandlerExceptionResolver {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public GlobalExceptionHandler() {
    }

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        response.addHeader("Content-Type", "application/json;charset=UTF-8");
        StringBuffer requestURL = request.getRequestURL();
        if (request.getQueryString() != null) {
            requestURL.append("?").append(request.getQueryString());
        }

        String completeURL = requestURL.toString();
        if (!(ex instanceof GameException)) {
            LOGGER.error("url:{},referer:{} exception", new Object[]{completeURL, request.getHeader("referer"), ex});
            LOGGER.error("系统异常!{}", ex);
        } else {
            GameException e = (GameException)ex;
            if (e != null) {
                if (e.getCode() == 1004) {
                    e.printStackTrace();
                    LOGGER.error("url:{},referer:{} exception: TrueMeException code:{}, msg:{}, param:{}, paramObj:{}", new Object[]{completeURL, request.getHeader("referer"), e.getCode(), e.getMsg(), e.getParam(), e.getParamObj()});
                    e.printStackTrace();
                } else {
                    LOGGER.error("url:{},referer:{} exception: TrueMeException code:{}, msg:{}, param:{}, paramObj:{}", new Object[]{completeURL, request.getHeader("referer"), e.getCode(), e.getMsg(), e.getParam(), e.getParamObj(), e});
                }
            }
        }

        ResponseBody responseBody = (ResponseBody)((HandlerMethod)handler).getMethodAnnotation(ResponseBody.class);
        Class<?> returnType = ((HandlerMethod)handler).getMethod().getReturnType();
        ModelAndView modelAndView;
        if (responseBody != null && returnType != byte[].class) {
            modelAndView = null;
            WebJsonBean webJsonBean;
            if (ex instanceof GameException) {
                if (((GameException)ex).getCode() == 1012) {
                    webJsonBean = new WebJsonBean(1012, JSONObject.toJSONString(((GameException)ex).getParamObj()), ((GameException)ex).getMsg());
                } else {
                    webJsonBean = new WebJsonBean(((GameException)ex).getCode(), ((GameException)ex).getMsg(), ((GameException)ex).getParamObj());
                }
            } else if (ex instanceof RuntimeException) {
                String msg = ex.getMessage();
                String taff = "com.morning.star.exception.GameException:";
                int index = msg.indexOf(taff);
                if (msg != null && index != -1) {
                    msg = msg.substring(index + taff.length(), msg.indexOf("\n"));
                    webJsonBean = new WebJsonBean(new CODE(1013, msg));
                } else {
                    webJsonBean = new WebJsonBean(CODE.API_IS_ERROR);
                }
            } else {
                webJsonBean = new WebJsonBean(CODE.SYSTEMERROR);
            }

            try {
                response.getWriter().write(JSON.toJSONString(webJsonBean));
            } catch (IOException var13) {
                LOGGER.error("GlobalExceptionHandler write cause IOException", var13);
            }

            return new ModelAndView();
        } else {
            modelAndView = new ModelAndView("error/error");
            if (ex instanceof GameException) {
                modelAndView.addObject("errorCode", ((GameException)ex).getCode());
                modelAndView.addObject("errorMsg", ((GameException)ex).getMsg());
            } else {
                modelAndView.addObject("errorMsg", ex.getMessage());
            }

            return modelAndView;
        }
    }
}
